import socket
import json
import struct
import threading
import time
from other.cfg import Config


class TCPClient:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.client_socket = None

    def connect(self):
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client_socket.connect((self.host, self.port))
        print('已连接到服务器')

    def send_data(self, data):
        # 将数据转换为JSON字符串
        json_str = json.dumps(data)
        # 添加头部信息
        header = b'nlane' + struct.pack('!I', len(json_str))
        cmd = header + json_str.encode('utf-8')
        print('send:', cmd)
        # 发送头部信息和数据
        self.client_socket.sendall(cmd)
        print('已发送数据')

    # def send(self, data):
    #     # 将数据转换为JSON字符串
    #     json_str = json.dumps(data)
    #     # 添加头部信息
    #     header = b'nlan5' + struct.pack('!I', len(json_str))
    #     cmd = header + json_str.encode('utf-8')
    #     print('send:', cmd)
    #     # 发送头部信息和数据
    #     self.client_socket.sendall(cmd)
    #     print('已发送数据')

    def receive_data(self):
        while True:
            # 接收头部信息
            header = b''
            while len(header) < 9:
                chunk = self.client_socket.recv(9 - len(header))
                if not chunk:
                    return None
                header += chunk

            # 检查头部信息
            if header[:5] != b'nlane':
                print('错误的头部信息')
                return None

            # 解析消息长度
            length = struct.unpack('!I', header[5:])[0]

            # 接收数据
            data = b''
            while len(data) < length:
                chunk = self.client_socket.recv(length - len(data))
                if not chunk:
                    return None
                data += chunk

            # 解析JSON数据
            json_data = json.loads(data.decode('utf-8'))
            print('接收到的数据:', json_data)
            if json_data['type'] == 'cfg':
                print(type(json_data))

    def test(self):
        # data_to_send = {'type': 'ai', 'status': 'once'}
        # client.send_data(data_to_send)
        # num = 0
        while True:
            # b = input('请输入人员:')
            # print('1.储物,2.中途储物,3.取物')
            a = input('请输入操作:')
            if a == '1':
                print('1.大柜格,2.小柜格')
                # c = input('请输入柜格:')
                # cabinetTypeId = 0
                # if c == '1':
                #     cabinetTypeId = 3
                # if c == '2':
                #     cabinetTypeId = 2
                # cmd = {"type": "storage_open_door", "cabinetTypeId": cabinetTypeId, "hostInfoId": "1", "userId": b}
                cmd = {'type': 'yy', 'date': 'da'}
                self.send_data(cmd)
            if a == '2':
                cmd = {"type": "halfway_storage_open_door", "hostInfoId": "1", "userId": b}
                self.send_data(cmd)
            if a == '3':
                cmd = {"type": "fetch_open_door", "hostInfoId": "1", "userId": b}
                self.send_data(cmd)

            # num += 1
            # 发送数据给服务器
            # data_to_send = {'type': 'camera', 'status': 'start'}
            # client.send_data(data_to_send)
            # time.sleep(8)
            # if num == 2:
            # break
            # num += 1
            # # 发送数据给服务器
            # data_to_send = {'type': 'ai2', 'status': 'once'}
            # client.send(data_to_send)
            # time.sleep(2)
            # if num == 3:
            #     break
            # num += 1
            # # 发送数据给服务器
            # data_to_send = {'type': 'ai3', 'status': 'once'}
            # client.send_data(data_to_send)
            # time.sleep(2)
            # if num == 3:
            #     break

    def close(self):
        if self.client_socket:
            self.client_socket.close()
            print('连接已关闭')


# 使用示例
if __name__ == "__main__":
    cfg = Config()
    print(cfg.res)
    host = cfg.res['tcp']['host']
    port = int(cfg.res['tcp']['port'])
    print(host, port)
    client = TCPClient(host, port)  # 修改为服务器的地址和端口
    client.connect()
    tt = threading.Thread(target=client.test, args=())
    tt.start()
    # client.test()
    # 接收服务器的响应
    client.receive_data()

    # 关闭连接
    client.close()
